package cn.dlc.com.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author dlc
 * @Date 2024/1/15
 * @Description TODO
 * @Version 0.0.1
 */
public class TestClass {

    public static void main(String[] args) throws Exception {
        String json = "{\n" +
                "  \"name\": \"jack\",\n" +
                "  \"age\": 12,\n" +
                "  \"habbit\": [{\n" +
                "    \"name\": \"1\",\n" +
                "    \"time\": \"1\"\n" +
                "  },{\n" +
                "    \"name\": \"2222\",\n" +
                "    \"time\": \"2222\"\n" +
                "  }],\n" +
                "  \"time\": {\n" +
                "    \"aa\": \"1\",\n" +
                "    \"bbb\": \"22\"\n" +
                "  }\n" +
                "}";


        JSONObject change = change(json);
        System.out.println(change.toJSONString());
    }

    private static JSONObject change(String json){

        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONObject jsonObjectAfter = JSONObject.parseObject(json);
        jsonObjectAfter.clear();

        Set<String> keySets = jsonObject.keySet();
        for (String keySet : keySets) {

            Object value = jsonObject.get(keySet);

            if(value instanceof JSONObject) {

                jsonObjectAfter.put(capitalizeFirstLetter(keySet), change(JSONObject.toJSONString(value)));

            }else if(value instanceof JSONArray){
                JSONArray array = (JSONArray)value;
                Iterator<Object> iterator = array.stream().iterator();
                JSONArray newArr = new JSONArray();
                while (iterator.hasNext()) {
                    JSONObject next = (JSONObject)iterator.next();
                    JSONObject change = change(JSONObject.toJSONString(next));
                    newArr.add(change);
                }
                jsonObjectAfter.put(capitalizeFirstLetter(keySet), newArr);
            } else {
                jsonObjectAfter.put(capitalizeFirstLetter(keySet), value);
            }
        }

        return jsonObjectAfter;
    }

    private static String capitalizeFirstLetter(String str) {
        if (str == null || str.length() == 0) {
            return "";
        } else {
            char firstChar = Character.toUpperCase(str.charAt(0));
            return firstChar + str.substring(1);
        }
    }
}
